using System;
using UnityEngine;
using System.Collections;


public class HerdBehaviour : HerdSteeringBehaviour
{
	private const float max_herd_distance = 1000.0f;
	
	float offset = 100f;
	float herdRadius = 150f;
	float needNewRange = 30f;
	
	private ArrayList agents;
	private ArrayList neighbours;
	
	private Vector3 position;

	public void Start()
	{
		//Get a list of agents from the game controller so that it can remove and add agents at will
		this.agents = (((GameController)GameObject.
			FindWithTag("GameController").GetComponent("GameController")).getAgents());		
	}
	
	public override Vector3 getSteering (HerderBehaviourScript herder)
	{
		position = herder.getPosition();
		Vector3 herderCurTargetPos = herder.getDestination();
		
		if((position - herderCurTargetPos).magnitude < needNewRange)
		{
			float herderOrientation = herder.rigidbody.rotation.eulerAngles.y;
			Vector3 wanderTargetPosition = new Vector3(0,herder.getPosition().y,0);
			double randomWanderAngle =  (UnityEngine.Random.value)*360; //gens a number between 0 and 360
			
			//sets the target, in the direction that the herder is facing, 'wanderDistance' away from the herder
			wanderTargetPosition.x = position.x + offset * (float)Math.Sin( (Math.PI/180) * herderOrientation);
			wanderTargetPosition.z = position.z + offset * (float)Math.Cos( (Math.PI/180) * herderOrientation);
			
			//moves the target to a random point, at the radius of the wander target
			wanderTargetPosition.x += herdRadius * (float)Math.Sin( (Math.PI/180) * randomWanderAngle);
			wanderTargetPosition.z += herdRadius * (float)Math.Cos( (Math.PI/180) * randomWanderAngle);
			
			return wanderTargetPosition;
		}
		return herderCurTargetPos;
	}
	
	
	//
	//	Returns the nearest agent as a target to herd
	//	@param HerderBehaviourScript herder
	//	@return Vector3 - target to herd
	public Vector3 getHerdTarget (HerderBehaviourScript herder)
	{
		float agent_dist = 0.0f;
		Vector3 agent_position = herder.getDestination();
		//Vector3 agent_direction;
		
		
        foreach (GameObject agent in agents) 
		{
			Vector3 temp_position = ((AgentBehaviourScript)agent.GetComponent("AgentBehaviourScript")).getPosition();
			float temp_dist = Vector3.Distance(this.position, temp_position);
			
			if(temp_dist > 0 && temp_dist < max_herd_distance)
			{			
				if(agent_dist == 0 || temp_dist < agent_dist)
				{
					//print("temp_dist: " + temp_dist + " temp_position: " + temp_position);
					agent_dist = temp_dist;
					agent_position = temp_position;
				}
			}
        }		
		return agent_position;
	}
}


